package com.apchernykh.rozhlasapp.player.fallback;

import java.util.Locale;

import com.apchernykh.rozhlasapp.interfaces.IProxyErrorsListener;
import com.apchernykh.rozhlasapp.utils.ConditionalLog;
import com.apchernykh.rozhlasapp.utils.StreamProxy;

import android.content.Context;

public class RozhlasProxyFallbackPlayer extends RozhlasNativeFallbackPlayer
		implements IFallbackPlayer, IProxyErrorsListener {

	String getProxyURL(String iUrl) {
		if (mProxy == null) {
			mProxy = new StreamProxy(this);
			mProxy.init();
			mProxy.start();
		}
		return String.format(Locale.US, "http://127.0.0.1:%d/%s",
				mProxy.getPort(), iUrl);

	}

	public RozhlasProxyFallbackPlayer(Context iContext, String iStreamUri) {
		super(iContext, iStreamUri);
		mStreamUri = getProxyURL(iStreamUri);
	}

	protected StreamProxy mProxy;

	@Override
	public void stop() {
		dispose();
		super.stop();
	}

	@Override
	public void onProxyError(String iMessage) {
		// Deliver all errors, coming from proxy only if MediaPlayer is still
		// alive and playing
		if (mSeparateThreadMediaPlayer != null) {
			ConditionalLog.e("onProxyError ", iMessage );
			onError(mSeparateThreadMediaPlayer, 567, 765);
			//proxy error is not always an inet failure :( 
			//TODO: implement distinction between internal proxy errors, closed client soctk from unavailable connection
//			RozhlasAppBaseFragmentActivity.mApplicationModel.mInetInfo
//					.signalInetFailure();
		}
		else
		{
			ConditionalLog.e("ignored onproxy error, since we have already stopped (" + iMessage + ")");
		}
	}
	
	@Override
	public void dispose() {
		if (mProxy != null) {
			mProxy.stop();
			mProxy = null;
		}
		super.dispose();
	}
}
